﻿import { useThreadScrolling } from '@/hooks/useThreadScrolling'
import { memo, useEffect } from 'react'
import { GenerateResponseButton } from './GenerateResponseButton'
import { useMessages } from '@/hooks/useMessages'
import { useShallow } from 'zustand/react/shallow'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
import { cn } from '@/lib/utils'
import { ArrowDown } from 'lucide-react'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { useAppState } from '@/hooks/useAppState'
import { MessageStatus } from '@janhq/core'
import { useModelProvider } from '@/hooks/useModelProvider'

const ScrollToBottom = ({
  threadId,
  scrollContainerRef,
}: {
  threadId: string
  scrollContainerRef: React.RefObject<HTMLDivElement | null>
}) => {
  const { t } = useTranslation()
  const appMainViewBgColor = useInterfaceSettings((state) => state.appMainViewBgColor)
  const { showScrollToBottomBtn, scrollToBottom } =
    useThreadScrolling(threadId, scrollContainerRef)
  const { messages } = useMessages(
    useShallow((state) => ({
      messages: state.messages[threadId],
    }))
  )

  const streamingContent = useAppState((state) => state.streamingContent)
  const selectedModel = useModelProvider((state) => state.selectedModel)
  const updateMessage = useMessages((state) => state.updateMessage)

  // Check if last message is a partial assistant response and show continue button (user interrupted)
  const isPartialResponse =
    messages.length >= 2 &&
    messages[messages.length - 1]?.role === 'assistant' &&
    messages[messages.length - 1]?.status === MessageStatus.Stopped &&
    messages[messages.length - 2]?.role === 'user' &&
    !messages[messages.length - 1]?.metadata?.tool_calls

  // Check if the partial response was generated by a different model
  const partialMessage = messages[messages.length - 1]
  const partialMessageModelId = partialMessage?.metadata?.modelId as string | undefined
  const hasModelSwitchedFlag = partialMessage?.metadata?.modelSwitched === true

  const currentModelMismatch = isPartialResponse &&
    partialMessageModelId !== undefined &&
    partialMessageModelId !== selectedModel?.id

  const isModelMismatch = isPartialResponse && (currentModelMismatch || hasModelSwitchedFlag)

  useEffect(() => {
    if (currentModelMismatch && !hasModelSwitchedFlag && partialMessage) {
      updateMessage({
        ...partialMessage,
        metadata: {
          ...partialMessage.metadata,
          modelSwitched: true,
        },
      })
    }
  }, [currentModelMismatch, hasModelSwitchedFlag, partialMessage, updateMessage])

  const showGenerateAIResponseBtn =
    ((messages[messages.length - 1]?.role === 'user' ||
      (messages[messages.length - 1]?.metadata &&
        'tool_calls' in (messages[messages.length - 1].metadata ?? {})) ||
      isPartialResponse ||
      isModelMismatch) &&
    !streamingContent)

  return (
    <div
      className={cn(
        'absolute z-0 -top-6 h-8 py-1 flex w-full justify-center pointer-events-none opacity-0 visibility-hidden',
        appMainViewBgColor.a === 1
          ? 'from-main-view/20 bg-gradient-to-b to-main-view backdrop-blur'
          : 'bg-transparent',
        (showScrollToBottomBtn || showGenerateAIResponseBtn) &&
          'visibility-visible opacity-100'
      )}
    >
      {showScrollToBottomBtn && (
        <div
          className="bg-main-view-fg/10 px-2 border border-main-view-fg/5 flex items-center justify-center rounded-xl gap-x-2 cursor-pointer pointer-events-auto"
          onClick={() => {
            scrollToBottom(true)
          }}
        >
          <p className="text-xs">{t('scrollToBottom')}</p>
          <ArrowDown size={12} />
        </div>
      )}
      {showGenerateAIResponseBtn && (
        <GenerateResponseButton threadId={threadId} isModelMismatch={isModelMismatch} />
      )}
    </div>
  )
}

export default memo(ScrollToBottom)
